<template>
  <div v-if="!isMain && !isView" class="add-equip-detail">
    <px-scrollbar class="add-equip-content">
      <px-button style="margin-top: 16px; margin-bottom: -4px" type="primary" icon="ArrowLeft" @click="backMainPage">返回</px-button>
      <EditDropDown dropdownTitle="缺失信息">
        <template v-slot:content>
          <px-form ref="formRef" :inline="true" :model="formValue" :rules="rules" label-position="right" label-width="120px">
            <px-row>
              <px-col :span="12">
                <px-form-item label="缺失编号">
                  <px-input placeholder="自动生成缺失编号" maxlength="50" disabled />
                </px-form-item>
              </px-col>
              <px-col :span="12">
                <EquipClassSelect :isRequired="true" :className="formValue.className" @changeClassName="changeClassName" />
              </px-col>
              <px-col :span="12">
                <px-form-item label="缺失类别" prop="missingType">
                  <px-radio-group v-model="formValue.missingType" @change="changeMissingType">
                    <px-radio v-for="(item, index) in props.missingTypeList" :key="index" :label="item.value">{{ item.name }}</px-radio>
                  </px-radio-group>
                </px-form-item>
              </px-col>
              <px-col v-if="formValue.missingType === 'EQP'" :span="12">
                <EquipSystemTree
                  propValue="systemId"
                  :isRequired="true"
                  :className="formValue.className"
                  :systemCode="formValue.systemId"
                  @changeAllSystemCodes="changeAllSystemCodes"
                  @changeSystemCodes="changeSystemCodes"
                  @clearSystem="clearSystem"
                />
              </px-col>
              <px-col v-if="formValue.missingType === 'EQP' && drawerType === 'edit'" :span="12">
                <px-form-item label="设备编号" prop="eqpId">
                  <px-input
                    v-model="formValue.eqpId"
                    placeholder="请点击选择"
                    maxlength="50"
                    disabled
                    style="width: calc(100% - 108px); margin-right: 8px"
                  />
                  <px-button type="primary" plain style="width: 100px" @click="dialogVisible = true">选择设备</px-button>
                </px-form-item>
              </px-col>
              <px-col v-if="formValue.missingType === 'EQP' && drawerType === 'edit'" :span="12">
                <px-form-item label="设备名称" prop="eqpName">
                  <px-input v-model="formValue.eqpName" placeholder="选择设备编号后自动带出" maxlength="50" disabled />
                </px-form-item>
              </px-col>
              <px-col v-if="formValue.missingType === 'EQP' && drawerType === 'edit'" :span="12">
                <px-form-item label="设备位置" prop="missingPositionDesc">
                  <px-input v-model="formValue.missingPositionDesc" placeholder="选择设备编号后带出" maxlength="50" disabled />
                </px-form-item>
              </px-col>
              <px-col v-if="formValue.missingType === 'EQP' && drawerType === 'add'" :span="24">
                <px-form-item label="设备编号" prop="eqpId" :rules="[{ required: true, validator: validateAttach, trigger: 'change' }]">
                  <px-button type="primary" plain style="width: 100px; margin-bottom: 10px" @click="multipleDialogVisible = true">选择设备</px-button>
                  <px-table
                    v-if="drawerType === 'add' && formValue.missingType === 'EQP'"
                    :data="formValue.equipmentList"
                    class="equip-table"
                    size="small"
                    max-height="400"
                    border
                  >
                    <px-table-column prop="eqpId" label="设备编号" min-width="120" show-overflow-tooltip />
                    <px-table-column prop="eqpName" label="设备名称" min-width="120" show-overflow-tooltip />
                    <px-table-column prop="positionNameAll" label="设备位置" min-width="150" show-overflow-tooltip />
                    <px-table-column label="详细位置" min-width="150">
                      <template #default="scope">
                        <px-input v-model="scope.row.eqpDetailPosition" placeholder="请输入详细位置" maxlength="50" clearable />
                      </template>
                    </px-table-column>
                    <px-table-column fixed="right" label="操作" width="100" align="center">
                      <template #default="scope">
                        <px-tooltip content="历史缺失" placement="top">
                          <px-button
                            v-has="'ALL_SAFEMANAGE_HISTORYDEFECT_VIEWPAGE'"
                            link
                            type="primary"
                            icon="Tickets"
                            @click="toHistoryDefeat('eqpId', scope.row.eqpId)"
                          />
                        </px-tooltip>
                        <px-tooltip content="删除" placement="top">
                          <px-button link type="primary" icon="Delete" @click="handleDelete(scope.$index)" />
                        </px-tooltip>
                      </template>
                    </px-table-column>
                  </px-table>
                </px-form-item>
              </px-col>
              <px-col v-if="formValue.missingType !== 'EQP'" :span="12">
                <px-form-item label="缺失位置" prop="missingPosition">
                  <px-cascader
                    ref="cascaderRef"
                    v-model="formValue.missingPosition"
                    filterable
                    clearable
                    style="width: 100%"
                    :options="missingPositionList"
                    :props="{ children: 'children', label: 'name', value: 'id', checkStrictly: true }"
                    placeholder="请选择缺失位置"
                    @focus="focusMissingPosition"
                    @change="changeMissingPosition"
                  />
                </px-form-item>
                <div v-if="props.drawerType === 'add' && formValue.missingPosition">
                  <px-button
                    v-has="'ALL_SAFEMANAGE_HISTORYDEFECT_VIEWPAGE'"
                    type="primary"
                    plain
                    text
                    style="position: relative; float: right; margin-top: -20px"
                    @click="toHistoryDefeat('position')"
                  >
                    历史缺失
                  </px-button>
                </div>
              </px-col>
              <px-col v-if="(drawerType === 'add' && formValue.missingType !== 'EQP') || drawerType === 'edit'" :span="12">
                <px-form-item label="详细位置" prop="missingDetailPosition">
                  <px-input v-model="formValue.missingDetailPosition" placeholder="请输入详细位置" maxlength="50" clearable />
                </px-form-item>
              </px-col>
              <px-col :span="12">
                <px-form-item label="缺失等级" prop="missingLevel">
                  <px-radio-group v-model="formValue.missingLevel">
                    <px-radio v-for="(item, index) in props.missingLevelList" :key="index" :label="item.value">{{ item.name }}</px-radio>
                  </px-radio-group>
                </px-form-item>
              </px-col>
              <px-col :span="12">
                <px-form-item label="缺失来源" prop="missingResource">
                  <px-radio-group v-model="formValue.missingResource">
                    <px-radio v-for="(item, index) in props.missingResourceList" :key="index" :label="item.value">{{ item.name }}</px-radio>
                  </px-radio-group>
                </px-form-item>
              </px-col>
              <px-col :span="12">
                <px-form-item label="责任人" prop="missingOwnerList">
                  <px-select-v2
                    v-model="formValue.missingOwnerList"
                    style="width: 100%"
                    multiple
                    collapse-tags
                    collapse-tags-tooltip
                    :max-collapse-tags="2"
                    filterable
                    clearable
                    :options="missingOwnerList"
                    placeholder="请选择责任人"
                    @focus="focusMissingOwner"
                  />
                </px-form-item>
              </px-col>
              <px-col :span="12">
                <px-form-item label="关联单号" prop="relationNumber">
                  <px-input v-model="formValue.relationNumber" placeholder="请输入关联单号" maxlength="50" clearable />
                </px-form-item>
              </px-col>
              <px-col :span="24">
                <px-form-item label="缺失描述" prop="missingDesc">
                  <px-input
                    v-model="formValue.missingDesc"
                    type="textarea"
                    :autosize="{ minRows: 2, maxRows: 4 }"
                    placeholder="请输入缺失描述"
                    maxlength="1000"
                    clearable
                  />
                </px-form-item>
              </px-col>
              <px-col :span="12">
                <px-form-item label="限期整改" prop="deadlineRectifyTime">
                  <px-date-picker
                    style="width: 100%"
                    v-model="formValue.deadlineRectifyTime"
                    type="date"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                    placeholder="请选择限期整改日期"
                  />
                </px-form-item>
              </px-col>
              <px-col :span="24">
                <px-form-item label="现场图片" prop="missingPictures">
                  <PhotoUpload
                    :photoType="photoType"
                    :photoData="{ moduleName: 'ifp-digitaltwins' }"
                    :photoList="formValue.missingPictures"
                    @changePhotoList="changePhotoList"
                    @savePhotoStatus="savePhotoStatus"
                  />
                </px-form-item>
              </px-col>
            </px-row>
          </px-form>
        </template>
      </EditDropDown>
    </px-scrollbar>
    <div class="info-form-btns">
      <px-button @click="backMainPage">取消</px-button>
      <px-button type="primary" :disabled="photoStatusFlag" @click="handleSubmit(formRef)">上报缺失</px-button>
    </div>
  </div>
  <!-- 选择设备弹窗-单选 -->
  <EquipIdSelectDialog
    :visible="dialogVisible"
    :className="formValue.className"
    :systemCodes="systemCodes"
    @closeEquipDialog="closeEquipDialog"
    @changeEqpId="changeEqpId"
  />
  <!-- 选择设备弹窗-多选 -->
  <EquipIdMultipleSelectDialog
    :dialogVisible="multipleDialogVisible"
    :className="formValue.className"
    :systemCodes="systemCodes"
    @closeEquipDialog="closeMultipleEquipDialog"
    @changeEqpIds="changeMultipleEqpId"
  />
</template>
<script setup lang="ts">
import { handleAlertDetailApi } from "@/api/alert";
import { editDefect, getDefect, reportDefect } from "@/api/defect";
import { getTableData } from "@/api/system/positionManage";
import { queryEqpById } from "@/api/equip/archive";
import PhotoUpload from "@/components/Upload/PhotoUpload.vue";
import EditDropDown from "@/views/all/equip/components/EditDropDown.vue";
import EquipClassSelect from "@/views/all/equip/components/EquipClassSelect.vue";
import EquipIdMultipleSelectDialog from "@/views/all/equip/components/EquipIdMultipleSelectDialog.vue";
import EquipIdSelectDialog from "@/views/all/equip/components/EquipIdSelectDialog.vue";
import EquipSystemTree from "@/views/all/equip/components/EquipSystemTree.vue";
import { PxMessage, PxMessageBox } from "px-ui";
import { computed, reactive, ref, toRefs, watch } from "vue";
import { useRouter } from "vue-router";
import { getEmployeeIdAndName } from "@/utils/pengxi";
import { cloneDeep, isEqual } from "@pureadmin/utils";

// 调用父级-返回主页、查询列表方法
const emits = defineEmits(["backMainPage", "queryTable"]);
// 父级传过来的值
const props = defineProps([
  "isMain",
  "isView",
  "drawerType",
  "isDraftVisible",
  "missingId",
  "missingLevelList",
  "missingTypeList",
  "missingResourceList",
  "alarmId"
]);
// 显示隐藏
const isMain = computed(() => props.isMain);
const isView = computed(() => props.isView);
// 页面本身的值
const router = useRouter();
const formRef = ref();
const state = reactive<any>({
  formValue: {
    // missingId: "",
    className: "",
    systemId: "",
    missingType: "EQP",
    missingLevel: "",
    missingOwnerList: [],
    missingResource: "CUSTOM",
    relationNumber: null,
    missingDesc: "",
    deadlineRectifyTime: "",
    missingPicture: "",
    missingDetailPosition: "",
    equipmentList: []
  },
  missingPositionList: [],
  photoStatusFlag: false,
  dialogVisible: false,
  multipleDialogVisible: false,
  systemCodes: [],
  photoType: "add",
  cascaderRef: null,
  missingOwnerList: [],
  differContent: null
});
const {
  formValue,
  missingPositionList,
  photoStatusFlag,
  dialogVisible,
  multipleDialogVisible,
  systemCodes,
  photoType,
  cascaderRef,
  missingOwnerList,
  differContent
} = toRefs(state);
// 表单校验规则
const rules = computed(() => ({
  missingType: [{ required: true, message: "缺失类别不能为空", trigger: "change" }],
  eqpId: [{ required: props.drawerType === "edit", message: "设备编号不能为空", trigger: "change" }],
  missingLevel: [{ required: true, message: "缺失等级不能为空", trigger: "change" }],
  missingPosition: [{ required: true, message: "缺失位置不能为空", trigger: "blur" }],
  missingOwnerList: [{ required: true, message: "责任人不能为空", trigger: "change" }],
  missingDesc: [{ required: true, message: "缺失描述不能为空", trigger: "blur" }]
}));
// 监视isMain和isView值
watch(isMain, async val => {
  if (!val && !props.isView) {
    formRef.value?.resetFields();
    focusMissingPosition();
    if (props.drawerType === "add" && !props.alarmId) {
      // const data = await getMissingId({});
      // formValue.value.missingId = data;
      formValue.value.className = "";
      formValue.value.systemId = "";
      formValue.value.missingType = "EQP";
      formValue.value.missingLevel = "";
      formValue.value.missingOwnerList = [];
      formValue.value.missingResource = "CUSTOM";
      formValue.value.relationNumber = "";
      formValue.value.missingDesc = "";
      formValue.value.deadlineRectifyTime = "";
      formValue.value.missingPicture = "";
      formValue.value.missingDetailPosition = "";
      photoType.value = "add";
    } else if (props.drawerType === "add" && props.alarmId) {
      // const missingIdVal = await getMissingId({});
      // formValue.value.missingId = missingIdVal;
      const alarmId = props.alarmId;
      const data = await handleAlertDetailApi({ alarmId });
      formValue.value.className = data?.className;
      formValue.value.systemId = data?.systemId;
      formValue.value.missingType = "EQP";
      formValue.value.missingResource = "ALARM";
      formValue.value.eqpId = data?.twinId;
      formValue.value.eqpName = data?.twinName;
      formValue.value.relationNumber = props.alarmId;
      formValue.value.missingDesc = data?.alarmContent;
      formValue.value.missingDetailPosition = "";
      const equipDetail = await queryEqpById({
        eqpId: data?.twinId
      });
      formValue.value.equipmentList = [equipDetail] || [];
      focusMissingOwner();
    } else if (props.drawerType === "edit") {
      getDetail();
      photoType.value = "edit";
    }
  } else {
    formValue.value.missingId = "";
    formValue.value.className = "";
    formValue.value.systemId = "";
    formValue.value.missingType = "EQP";
    formValue.value.missingLevel = "";
    formValue.value.missingOwnerList = [];
    formValue.value.missingResource = "CUSTOM";
    formValue.value.relationNumber = "";
    formValue.value.missingDesc = "";
    formValue.value.deadlineRectifyTime = "";
    formValue.value.missingPicture = "";
    formValue.value.eqpId = "";
    formValue.value.eqpName = "";
    formValue.value.missingPosition = "";
    formValue.value.missingPositionDesc = "";
    formValue.value.missingDetailPosition = "";
    formValue.value.missingPictures = [];
  }
  differContent.value = cloneDeep(formValue.value);
});
// 监视isMain和isView值
watch(isView, async val => {
  if (!val && !props.isMain) {
    formRef.value?.resetFields();
    systemCodes.value = [];
    focusMissingPosition();
    if (props.drawerType === "edit") {
      getDetail();
      photoType.value = "edit";
    }
  }
});
// 校验文档文件
const validateAttach = (rule, value, callback) => {
  if (formValue.value.equipmentList.length <= 0) {
    callback(new Error("选择设备不能为空"));
  }
  callback();
};
// 获取当前科室责任人接口
const focusMissingOwner = async () => {
  const param = formValue.value.className ? [formValue.value.className] : [];
  const data = await getEmployeeIdAndName(param);
  missingOwnerList.value = JSON.parse(JSON.stringify(data));
};
const handleDelete = index => {
  formValue.value.equipmentList?.splice(index, 1);
};
// 获取详情
const getDetail = async () => {
  const params = {
    missingId: props.missingId
  };
  const data = await getDefect(params);
  formValue.value = data;
  formValue.value.missingOwnerList = data.missingOwnerList.map(Number);
  focusMissingOwner();
  if (data.missingPictureList && data.missingPictureList.length > 0) {
    data.missingPictureList.forEach(item => {
      item.url = item.fileUrl;
    });
    formValue.value.missingPictures = data.missingPictureList;
  } else {
    formValue.value.missingPictures = [];
  }
  differContent.value = cloneDeep(formValue.value);
};
// 缺失位置聚焦时
const focusMissingPosition = async () => {
  const missingPosition = await getTableData({});
  missingPositionList.value = missingPosition || [];
};
// 返回主页面
const backMainPage = () => {
  const differCont = cloneDeep(formValue.value);
  if (isEqual(differContent.value, differCont)) {
    formRef.value?.resetFields();
    differContent.value = null;
    emits("backMainPage");
    return;
  }
  PxMessageBox.confirm("确认退出页面？退出后内容不会保存", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
    draggable: true
  })
    .then(async () => {
      formValue.value.equipmentList = [];
      formRef.value?.resetFields();
      differContent.value = null;
      emits("backMainPage");
    })
    .catch(() => {});
};
// 关闭子级设备dialog弹窗
const closeEquipDialog = () => {
  dialogVisible.value = false;
};

const closeMultipleEquipDialog = () => {
  multipleDialogVisible.value = false;
};

// 改变类型
const changeMissingType = () => {
  if (formValue.value.missingType === "EQP") {
    formValue.value.missingPosition = "";
    delete formValue.value.missingPositionDesc;
  } else {
    formValue.value.missingPosition = "";
    delete formValue.value.eqpId;
    delete formValue.value.eqpName;
  }
  formRef.value?.resetFields(["missingOwnerList"]);
};
// 缺失位置改变
const changeMissingPosition = val => {
  formValue.value.missingPosition = val && val.length > 0 ? val[val.length - 1] : "";
  const detail = findNodeByCode(missingPositionList.value, formValue.value.missingPosition);
  formValue.value.missingOwnerList = detail?.principalIds?.split(",").map(Number) || [];
  focusMissingOwner();
  cascaderRef.value.togglePopperVisible();
};
// 提交
const handleSubmit = async (formEl: any) => {
  if (!formEl) return;
  await formEl.validate(async valid => {
    if (valid) {
      PxMessageBox.confirm("确认上报缺失吗？", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning",
        draggable: true
      })
        .then(async () => {
          formValue.value.missingOwnerNameList = missingOwnerList.value
            .filter(item => formValue.value.missingOwnerList.includes(item.userId))
            .map(item => item.username + "-" + item.realName);
          const params = JSON.parse(JSON.stringify(formValue.value));
          const userInfo = JSON.parse(localStorage.getItem("userInfo"));
          params.reportUser = userInfo.username + "-" + userInfo.realName;
          params.deadlineRectifyTime = formValue.value.deadlineRectifyTime ? formValue.value.deadlineRectifyTime + " 23:59:59" : null;
          const arr = [];
          if (formValue.value.missingPictures && formValue.value.missingPictures.length > 0) {
            formValue.value.missingPictures.forEach(item => {
              if (item?.id) {
                arr.push(item.id);
              } else if (item?.response.data.id) {
                arr.push(item.response.data.id);
              }
            });
          }
          params.missingPicture = arr.toString();
          if (params.missingType !== "EQP") {
            params.systemId = "";
            params.systemName = "";
            params.systemNameAll = "";
          }
          if (props.drawerType === "add") {
            if (formValue.value.missingType === "EQP") {
              const { equipmentList } = formValue.value;
              const eqpList = equipmentList?.map(item => ({
                eqpId: item.eqpId,
                eqpName: item.eqpName,
                missingPosition: item.positionCode,
                eqpDetailPosition: item.eqpDetailPosition
              }));
              params.equipmentList = eqpList;
            }
            await reportDefect(params);
            PxMessage.success("新增缺失成功");
            formValue.value.equipmentList = [];
            emits("backMainPage");
            emits("queryTable");
          } else if (props.drawerType === "edit") {
            await editDefect(params);
            PxMessage.success("编辑缺失成功");
            emits("backMainPage");
            emits("queryTable");
          }
        })
        .catch(() => {});
    }
  });
};
// 跳转到历史缺失
const toHistoryDefeat = (type, id?: number) => {
  if (type === "eqpId") {
    router.push(`/all/safeManage/historyDefect?eqpId=${id || formValue.value.eqpId}&missingType=${formValue.value.missingType}`);
  } else if (type === "position") {
    router.push(`/all/safeManage/historyDefect?missingPosition=${formValue.value.missingPosition}&missingType=${formValue.value.missingType}`);
  }
};

// 外部封装好的组件
// 新的图片列表
const changePhotoList = val => {
  formValue.value.missingPictures = val;
};
// 图片是否上传完，是否可以保存
const savePhotoStatus = val => {
  photoStatusFlag.value = val;
};
// 清空设备相关内容
const resetEquip = () => {
  if (formValue.value.missingType === "EQP") {
    formValue.value.missingPosition = "";
    formValue.value.missingPositionDesc = "";
  } else {
    formValue.value.missingPosition = "";
  }
};
// 外部封装好的组件
// 科室组件调用父组件
const changeClassName = (val, isOnlyClass) => {
  formValue.value.className = val;
  formValue.value.equipmentList = [];
  systemCodes.value = [];
  if (!isOnlyClass) {
    formRef.value?.resetFields(["systemId", "eqpId", "eqpName", "missingOwnerList"]);
  }
};
// 系统组件调用父组件
const changeAllSystemCodes = (val, val2, val3, val4) => {
  formValue.value.className = val2;
  formValue.value.systemId = val3;
  systemCodes.value = val4;
  formValue.value.equipmentList = [];
  formRef.value?.resetFields(["eqpId", "eqpName"]);
};
// 系统组件调用父组件
const changeSystemCodes = (val, val2) => {
  formValue.value.systemId = val;
  systemCodes.value = val2;
  formValue.value.equipmentList = [];
  formRef.value?.resetFields(["eqpId", "eqpName"]);
};
// 系统组件值改变触发
const clearSystem = val => {
  systemCodes.value = [];
  formRef.value?.resetFields(["systemId", "eqpId", "eqpName"]);
};
// 改变设备编号
const changeEqpId = equipDetail => {
  formValue.value.className = equipDetail?.className || "";
  formValue.value.systemId = equipDetail?.systemCode || "";
  formValue.value.eqpId = equipDetail?.eqpId || "";
  formValue.value.eqpName = equipDetail?.eqpName || "";
  formValue.value.missingPosition = equipDetail?.positionCode || "";
  formValue.value.missingPositionDesc = equipDetail?.positionNameAll || "";
  formValue.value.missingOwnerList = equipDetail?.principalId || [];
};
// 改变设备编号多选
const changeMultipleEqpId = val => {
  if (val) {
    formValue.value.equipmentList = formValue.value.equipmentList?.concat(val)?.filter((obj, index, self) => {
      return self.map(x => x.eqpId).indexOf(obj.eqpId) === index;
    });
    const arr = formValue.value.equipmentList?.map(item => item.principalId);
    formValue.value.missingOwnerList = [...new Set(arr)].filter(item => item !== null);
  }
};
const findNodeByCode = (list, id) => {
  for (let i in list) {
    if (list[i].code === id) {
      return list[i];
    }
    if (list[i].children) {
      let node = findNodeByCode(list[i].children, id);
      if (node !== undefined) {
        return node;
      }
    }
  }
};
</script>
<style lang="scss" scoped>
@import url("@/views/all/equip/scss/add-detail.scss");
</style>
